<?php

namespace api\modules\v1\models;
use api\func\func;
use Yii;
use api\common\models\Common;
use api\common\models\Mar;
use yii\data\Pagination;

class Reward extends Common
{
    public static function tableName()
    {
        return '{{%reward_app}}';
    }

    public function rules()
    {
        return [
            ['rereward_id', 'required'],
            ['rereward_id', 'integer'],
            ['rereward_id', 'validateRerewardUid'],

            ['catid', 'required'],
            ['catid', 'integer'],

            ['news_id', 'required'],
            ['news_id', 'integer'],
            ['news_id', 'validateNewsId'],

            ['money', 'required'],
            ['money', 'double'],
            ['money','match','pattern'=>'/^[0-9]+(.[0-9]{1,2})?$/'],

            ['pay_type', 'required'],
            ['pay_type', 'integer'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'order_num' => Yii::t('app', '支付订单号'),
            'reward_id' => Yii::t('app', '打赏人'),
            'rereward_id' => Yii::t('app', '被打赏人'),
            'catid' => Yii::t('app', '栏目id'),
            'news_id' => Yii::t('app', '文章id'),
            'money' => Yii::t('app', '金额'),
            'status' => Yii::t('app', '状态'),
            'pay_type' => Yii::t('app', '支付方式'),
            'time' => Yii::t('app', '打赏时间'),
        ];
    }

    public function validateRerewardUid($attribute, $params){
        if($this->rereward_id == 0 || $this->rereward_id == '' || $this->rereward_id == null){ //后台编辑发布的文章 金额进入公共账户
            if(!$user = User::findOne(['phone'=>Yii::$app->params['alipay_public_account']])){
                $this->addError($this->rereward_id,'被打赏用户不存在');
                return false;
            }else{
                $this->rereward_id = $user['id'];
            }
        }else{
/*            if(!User::findOne(['id'=>$this->rereward_id])){
                $this->addError($this->rereward_id,'被打赏用户不存在');
                return false;
            }*/
            $news_table = '{{%'.News::getTable($this->catid).'}}'; //验证该文章是否属于该被打赏人
            $news = new Mar($news_table);
            if(!$news->findOnex($news_table,['id'=>$this->news_id,'thirdid'=>$this->rereward_id])) {
                $this->addError($this->rereward_id,'信息不匹配');
                return false;
            }
        }

        if($this->rereward_id == Yii::$app->user->identity->id){
            $this->addError($this->rereward_id,'不能打赏自己');
            return false;
        }
        return true;
    }

    public function validateNewsId($attribute, $params)
    {
        if(!Category::findOne(['catid'=>$this->catid])){
            $this->addError($this->catid,'栏目id:'.$this->catid.'不存在');
            return false;
        }

        //验证文章id是否存在
        $news_model = News::getTable($this->catid);
        $db = \Yii::$app->db;
        if (!$rows = $db->createCommand('SELECT id,catid,thirdid FROM {{%' . $news_model . '}} where id = ' . $this->news_id)->queryOne()) {
            $this->addError($this->news_id,'文章id:'.$this->news_id.'不存在');
            return false;
        }

        //验证 文章是否在栏目里面
        if($rows['catid'] != $this->catid){
            $this->addError($this->news_id,'文章id:'.$this->news_id.'与栏目id:'.$this->catid.'不匹配');
            return false;
        }

        return true;
    }

    public function beforeSave($insert = true)
    {
        if ($this->isNewRecord) {
            $this->reward_id = Yii::$app->user->identity->id;
            $this->order_num = 'DS'.date('YmdHis',time()).uniqid();
            $this->status = 0;
            $this->time = date('Y-m-d H:i:s',time());
        }
        return true;
    }

    public function getList(){
        $uid = Yii::$app->user->identity->id;
        $query = (new \yii\db\Query())
            ->select(['b.nickname','b.phone','b.head_img','a.reward_id','a.rereward_id','a.money','a.time'])
            ->from('{{%reward_app}} as a')
            ->join('LEFT JOIN','{{%user_app}} as b','a.rereward_id=b.id')
            //->where("(a.rereward_id={$uid} or a.reward_id = {$uid}) and a.`status` = 1");
            ->where("(a.reward_id = {$uid}) and a.`status` = 1");

        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('time desc')
            ->all();
        $this->serializePagination($pagination);
        foreach($data as &$value){
            $value['money'] = number_format($value['money'],2);
            $value['nickname'] = $value['nickname'] !='' ? $value['nickname']: func::replace_phone($value['phone']);
            unset($value['phone']);
            if($value['reward_id'] == $uid){ //打赏
                $value['type'] = 1;
            }elseif($value['rereward_id'] == $uid){//被打赏
                $value['type'] = 2;
            }
            unset($value['reward_id']);
            unset($value['rereward_id']);
            $value['head_img'] = $value['head_img'] !='' ? $value['head_img'] : '';
        }

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;

        return $_data;
    }

}
